package com.example.chat.config;

import com.dragonsoftbravo.libs.MyCls;
import com.example.chat.model.Employee;
import com.example.chat.model.vo.TokenInfoVo;
import com.example.chat.service.JwtService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * @author pq
 * @date 2022/8/17 10:47
 * @description 自动生成数据库的creatUser和modifyUser，需要在启动类上添加@EnableJpaAuditing注解，
 * BaseEntity加上@CreatedBy和@LastModifiedBy注解，@EntityListeners中加上AuditingEntityListener.class
 * @modified
 **/
@Configuration
public class JpaAuditorGenerateConfig implements ApplicationContextAware, AuditorAware<String> {
    @Value("${jwt.login.response.header}")
    private String jwtHeader;

    private static ApplicationContext applicationContext;

    @Resource
    private JwtService jwtService;

    @Override
    public Optional<String> getCurrentAuditor() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes request= (ServletRequestAttributes) requestAttributes;
        if(Objects.isNull(request)){
            return Optional.of("初始化");
        }
        HttpServletRequest req=request.getRequest();
        String token = req.getHeader(jwtHeader);
        TokenInfoVo tokenInfoVo = jwtService.unSignToken(token);
        return Optional.of(tokenInfoVo.getEmpId());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (JpaAuditorGenerateConfig.applicationContext == null) {
            JpaAuditorGenerateConfig.applicationContext = applicationContext;
        }
    }

    /**
     * @Author: luoling
     * @Description: 通过name获取 Bean
     * @Data: 2021/12/10 17:36
     * @Param: [clazz]
     * @Return: java.lang.Object
     */
    public static Object getBean(Class clazz){
        return getApplicationContext().getBean(clazz);
    }

    /**
     * @Author: luoling
     * @Description: 获取applicationContext
     * @Data: 2021/12/10 17:36
     * @Param: []
     * @Return: org.springframework.context.ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

